package com.dimples.dd.security.config;

import com.dimples.dd.common.constant.DDConstant;
import com.dimples.dd.security.core.interceptor.DDServerProtectInterceptor;
import com.dimples.dd.security.core.interceptor.HeaderInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author zhongyj <1126834403@qq.com><br/>
 * @date 2024/6/7
 */
@Slf4j
public class DDServerProtectConfigure implements WebMvcConfigurer {

    @Bean
    @ConditionalOnMissingBean(value = PasswordEncoder.class)
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        log.info(DDConstant.CONFIG_LOG, "Add Interceptors HeaderInterceptor");
        // 保证HeaderInterceptor在ServerProtectInterceptor之前运行
        registry.addInterceptor(headerInterceptor()).addPathPatterns("/**");

        log.info(DDConstant.CONFIG_LOG, "Add Interceptors ServerProtectInterceptor");
        registry.addInterceptor(ddServerProtectInterceptor()).addPathPatterns("/**");
    }

    @Bean
    public HandlerInterceptor ddServerProtectInterceptor() {
        return new DDServerProtectInterceptor();
    }

    /**
     * 自定义请求头拦截器
     */
    @Bean
    public HeaderInterceptor headerInterceptor() {
        return new HeaderInterceptor();
    }
}
